package com.easy.controller;

import cn.hutool.db.PageResult;
import com.easy.bean.PostBean;
import com.easy.service.PostService;
import com.easy.util.Page;
import com.easy.util.PageRequest;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/post")
public class PostController {

    @Autowired
    private PostService postService;

    @PostMapping("add")
    public Result add(@RequestBody PostBean post) {
        PostBean post_data = postService.add(post);
        return Result.success(post_data);
    }

    @PutMapping
    public Result edit(@RequestBody PostBean post) {
        PostBean post_data = postService.update(post);
        return Result.success(post_data);
    }


    // 根据用户ID查询帖子
    @GetMapping("/users/{userId}/posts")
    public Result getPostsByUser(@PathVariable("userId") Integer userId) {
        return Result.success(postService.getPostsByUserId(userId));
    }

    @GetMapping("/type/{typeId}")
    public Result listByType(@PathVariable("typeId") Integer typeId) {
        List<PostBean> posts = postService.listByType(typeId);
        return Result.success(posts);
    }

    @GetMapping("search")
    public Result searchByTitle(@RequestParam("keyword") String keyword, Page page) {
        postService.searchByTitle(keyword, page);
        return Result.success(page);
    }

    @GetMapping("list")
    public Result list() {  // 移除参数，直接查询所有已发布帖子
        PostBean post = new PostBean();
        post.setStatus("published");
        List<PostBean> posts = postService.list(post);
        return Result.success(posts);
    }

    @GetMapping("page")
    public Result page(Page page,PostBean post){
        postService.page(page, post);
        return Result.success(page);
    }
    @GetMapping("listPage")
    public Result listPage(Page page,PostBean post) {
        postService.listPage(page, post);
        return Result.success(page);
    }
    @DeleteMapping("{id}")
    public Result del(@PathVariable("id") Integer id) {
        int result = postService.del(id);
        return result > 0 ? Result.success("删除成功") : Result.success("删除失败");
    }
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        int result = postService.delete(id);
        return result > 0 ? Result.success("删除成功") : Result.success("删除失败");
    }

    @GetMapping("{id}")
    public Result getById(@PathVariable("id") Integer id) {
        PostBean post = postService.get(id);
        return post != null ? Result.success(post) : Result.success("帖子不存在");
    }
}